/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package co.elastic.apm.agent.awslambda.lambdas;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse;

import java.util.Map;

public class ApiGatewayV2LambdaFunction extends AbstractFunction<APIGatewayV2HTTPEvent, APIGatewayV2HTTPResponse> {

    public static final String EXPECTED_BODY = "This is some body";
    public static final String EXPECTED_RESPONSE_HEADER_1_KEY = "EXPECTED_HEADER_1_KEY";
    public static final String EXPECTED_RESPONSE_HEADER_1_VALUE = "EXPECTED_HEADER_1_VALUE";
    public static final String EXPECTED_RESPONSE_HEADER_2_KEY = "EXPECTED_HEADER_2_KEY";
    public static final String EXPECTED_RESPONSE_HEADER_2_VALUE = "EXPECTED_HEADER_2_VALUE";
    public static final int EXPECTED_STATUS_CODE = 202;
    public static final int ERROR_STATUS_CODE = 505;

    @Override
    public APIGatewayV2HTTPResponse handleRequest(APIGatewayV2HTTPEvent httpEvent, Context context) {
        createChildSpan();

        APIGatewayV2HTTPResponse response = new APIGatewayV2HTTPResponse();
        response.setBody(EXPECTED_BODY);
        response.setHeaders(Map.of(EXPECTED_RESPONSE_HEADER_1_KEY, EXPECTED_RESPONSE_HEADER_1_VALUE, EXPECTED_RESPONSE_HEADER_2_KEY, EXPECTED_RESPONSE_HEADER_2_VALUE));

        if (((TestContext) context).shouldSetErrorStatusCode()) {
            response.setStatusCode(ERROR_STATUS_CODE);
        } else {
            response.setStatusCode(EXPECTED_STATUS_CODE);
        }

        raiseException(context);

        return response;
    }
}
